<?php 

	class Default_TableController extends System_Controller
	{
        private $projectInfo;
        private $jsonData;

        public function preDispatch()
        {
             $auth = Zend_Auth::getInstance();
             if(!$auth->hasIdentity())
             {
                 $this->_redirect('/user/login');
             }

            $this->projectInfo =  new Zend_Session_Namespace('projectInfo');

            if(isset($_POST['tableAjax']))
            {
                $this->jsonData = $_POST['tableAjax'];
                $this->jsonData = stripslashes($this->jsonData);
                $this->jsonData = json_decode($this->jsonData, true);
            }           
        }
        
        public function indexAction()
        {
           $this->_helper->layout()->disableLayout();

           if($this->_request->isPost())
            {
                $postData = $this->_request->getPost();

                $table = new Table();
                $result = $table->getByProjectId($postData['projectId']);
                $this->view->tables = $result;
                $this->projectInfo->id = $postData['projectId'];
                $this->view->projectId = $this->projectInfo->id;
           }
        }

        public function contentAction()
        {
            $this->_helper->layout()->disableLayout();

            if($this->_request->isPost())
            {
                $postData = $this->_request->getPost();

                //testa se os dados forma passados por JSON
                if(isset($this->jsonData))
                {
                    $this->_helper->viewRenderer->setNoRender(true);

                    if($this->jsonData['action'] == 'salvarDados')
                    {
                        $this->saveData($this->transformInArray($this->jsonData));
                        echo json_encode(array('status'=>1,'resultado'=>'Dados salvos com sucesso.'));
                        die;
                    }else if($this->jsonData['action']=='dropColumn')
                    {
                        $projectsTables = new ProjectsTables();
                        $tableMeta = $projectsTables->getTableMetadataById($this->jsonData['tableId']);
                        $table = new Tables($tableMeta[0]['name']);
                        $table->removeCollumn($this->jsonData['columnName']);
                        echo json_encode(array('status'=>1,'resultado'=>'Coluna Removida com sucesso.'));
                        die;
                    }
                    //exclui a tabela do banco
                    $table = new Table();
                    $table->dropOuterTable($this->jsonData['id']);
                    echo json_encode(array('status'=>1,'resultado'=>'Dados salvos com sucesso.'));
                    die;
                }

                //acões da tabela são gerenciadas aqui como adicionar coluna
                if(isset($postData['action']))
                {   
                    if($postData['action'] == 'addCollumn')
                        $this->addCollumn($postData);
                }

                $table = new Table();
                $tableContent = $table->getOuterTable($postData['tableId']);

                $this->view->table = $tableContent;
                $this->view->tableId = $postData['tableId'];
                $this->view->projectId = $this->projectInfo->id;
            }              
        }

        private function transformInArray($json)
        {
            $finalArray = array();
            //linha atual
            $currRow =0;
            //ultima linha
            $lastRow =0;
            //action
            $action = 'alter';
            foreach($json as $cellId => $cellValue)
            {
                $cellIdArray = explode('-',$cellId);
                //se o id tem 3 elementos entao é com o banco                
                if(isset($cellIdArray[2]))
                {   
                    //id da linha
                    $currRow = $cellIdArray[1];
                    //nome da coluna
                    $cellName = $cellIdArray[0];
                    //se trocou de linha entra
                    if($currRow!=$lastRow || $currRow==0)
                    {                        
                        $finalArray['dbQuery'][$lastRow]['action'] = $action;
                        $lastRow = $currRow;
                    }

                    //insere no array a célula
                    if(isset($cellIdArray[3]))
                    {
                        $finalArray['dbQuery'][$lastRow][$cellName]['cellType']  = $cellValue; 
                    }
                    else
                    {
                        $finalArray['dbQuery'][$lastRow][$cellName]['cellName'] = $cellValue;
                     
                    }
                    $action = $cellIdArray[2];
                }
                //se nao tem 3 elementos sao dados adicionais
                else
                {
                    if($cellIdArray[0] == 'tableInfo')
                    {
                        $cellValueArray = explode('_',$cellValue);
                        $finalArray['info']['projectId'] = $cellValueArray[1];
                        $table = new Table();
                        $tableContent = $table->getContentById($cellValueArray[3]);
                        $finalArray['info']['tableName'] = $tableContent['name'];
                    }
                }
            }
            //adiciona a última linha
            $finalArray['dbQuery'][$lastRow]['action'] = $action;
            return $finalArray;
        }

        //salva altera a tabela 
        private function saveData($data)
        {
            $table = new Table();

            if(is_array($data))
            {
                foreach($data['dbQuery'] as $idQuery => $query)
                {
                    if($query['action'] == 'alter')
                    {
                        unset($query['action']);
                        $table->alterOuterTableDefinition($data['info']['projectId'],$data['info']['tableName'],$query);
                    }
                    elseif($query['action'] == 'insert')
                    {
                        unset($query['action']);
                        $table->insertOuterData($data['info']['tableName'],$query);
                    }
                    elseif($query['action'] == 'update')
                    {              
                        unset($query['action']);      
                        $tables = new Tables($data['info']['tableName']);
                        $tables->updateRow($query,$idQuery);
                    }
                }
                return true;
            }
            return false;
        }

        private function addCollumn($collumnData)
        {
            $table = new Table();
            $tableData = $table->getOuterTableInfoById($collumnData['tableId']);
            $table->addCollumnOuterTable($collumnData['projectId'],$tableData[0]['name'],$collumnData['collumnName'],$collumnData['collumnType']);
        }

        public function createAction()
        {
            $form = new ZendJean_form_CreateTable();
    
            if($this->_request->isPost())
            {
                $table = new Table();
                
                $postData = $this->_request->getPost();
                if(!$form->isValid($postData))
                { 
                    $this->view->error = 'Algum campo est&aacute; incorreto.';   
                }
                else if($table->hasTable($postData['tableName']))
                {
                    $this->view->error = 'Projeto j&aacute; cadastrado.';
                }
                else
                {
                    $table->insertTable($postData['tableName'],
                                        $postData['tableDescription'],
                                        $this->projectInfo->id);
                    $this->view->message = 'Dados devidamente cadastrados!';
                }
            }
        }
    }      
?>
            